import dayjs from 'dayjs';

/**
 * 计算耗时
 * @param beginTime 毫秒
 * @param endTime 毫秒
 */
function beginTimeEndTimeConvert(beginTime: number, endTime: number) {
  const totalTime = Math.floor(endTime / 1000) - Math.floor(beginTime / 1000);
  return formatTimeFromSeconds(totalTime);
}

/**
 * 格式化秒
 * @param number  value 秒数
 * @return string result 格式化后的字符串: 几天几时几分几秒
 */
function formatTimeFromSeconds(value: number) {
  let theTime = value; //秒 需要转换的时间秒
  let theTime1 = 0; // 分
  let theTime2 = 0; // 小时
  let theTime3 = 0; // 天
  if (theTime >= 60) {
    //大于等于60秒
    theTime1 = Math.floor(theTime / 60);
    theTime = theTime % 60;
    if (theTime1 >= 60) {
      //大于等于60分钟
      theTime2 = Math.floor(theTime1 / 60);
      theTime1 = theTime1 % 60;
      if (theTime2 >= 24) {
        //>大于等于24小时
        theTime3 = Math.floor(theTime2 / 24);
        theTime2 = theTime2 % 24;
      }
    }
  }
  var result = '';
  if (theTime > 0) {
    result = '' + theTime + '秒';
  }
  if (theTime1 > 0) {
    result = '' + theTime1 + '分' + result;
  }
  if (theTime2 > 0) {
    result = '' + theTime2 + '小时' + result;
  }
  if (theTime3 > 0) {
    result = '' + theTime3 + '天' + result;
  }
  return result;
}

/**
 * 格式化秒
 * @param number  value 毫秒数
 * @return string result 格式化后的字符串: 几天几时几分几秒
 */
function formatSeconds(value: number) {
  if (Math.floor(value / 1000) === 0) {
    return '0秒';
  }
  return formatTimeFromSeconds(Math.floor(value / 1000));
}

/**
 *格式化分钟
 * @param number  value 分钟
 * @return string result 格式化后的字符串: 几天几时几分
 */
function formatMinutes(value: number) {
  let theTime1 = value; // 分
  let theTime2 = 0; // 小时
  let theTime3 = 0; // 天

  if (theTime1 >= 60) {
    //大于等于60分钟
    theTime2 = Math.floor(theTime1 / 60);
    theTime1 = theTime1 % 60;
    if (theTime2 >= 24) {
      //大于等于24小时
      theTime3 = Math.floor(theTime2 / 24);
      theTime2 = theTime2 % 24;
    }
  }
  var result = '';
  if (theTime1 > 0) {
    result = '' + theTime1 + '分' + result;
  }
  if (theTime2 > 0) {
    result = '' + theTime2 + '小时' + result;
  }
  if (theTime3 > 0) {
    result = '' + theTime3 + '天' + result;
  }
  return result;
}
/**
 *timestamp时间字符串转年月日
 * @param timestamp时间戳字符串
 */
function formatTimestampStr(
  timestamp?: string | number,
  formatStr: string = 'YYYY-MM-DD HH:mm:ss',
  emptyStr: string = '_',
): string {
  if (typeof timestamp === 'string') {
    return timestamp ? dayjs(Number(timestamp)).format(formatStr) : emptyStr;
  }

  return timestamp ? dayjs(timestamp).format(formatStr) : emptyStr;
}

export { beginTimeEndTimeConvert, formatSeconds, formatMinutes, formatTimestampStr };
